package cn.com.lyj6851.modules.category.controller;

import cn.com.lyj6851.api.MyShopException;
import cn.com.lyj6851.constant.ShopConstants;
import cn.com.lyj6851.logging.aop.AopLog;
import cn.com.lyj6851.modules.category.domain.YdyStoreCategory;
import cn.com.lyj6851.modules.category.service.YdyStoreCategoryService;
import cn.com.lyj6851.modules.category.service.dto.YdyStoreCategoryDto;
import cn.com.lyj6851.modules.category.service.dto.YdyStoreCategoryQueryCriteria;
import cn.com.lyj6851.modules.product.domain.YdyStoreProduct;
import cn.com.lyj6851.modules.product.service.YdyStoreProductService;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
*
 * @author Administrator
 */
@Api(tags = "商城:商品分类管理")
@RestController
@RequestMapping("api")
public class StoreCategoryController {


    private final YdyStoreCategoryService storeCategoryService;
    private final YdyStoreProductService storeProductService;


    public StoreCategoryController(YdyStoreCategoryService storeCategoryService,
                                   YdyStoreProductService storeProductService) {
        this.storeCategoryService = storeCategoryService;
        this.storeProductService = storeProductService;
    }

    @AopLog("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/ydyStoreCategory/download")
    @PreAuthorize("@el.check('admin','STORECATEGORY_SELECT')")
    public void download(HttpServletResponse response, YdyStoreCategoryQueryCriteria criteria) throws IOException {
        storeCategoryService.download(storeCategoryService.queryAll(criteria), response);
    }


    @AopLog("查询商品分类")
    @ApiOperation(value = "查询商品分类")
    @GetMapping(value = "/ydyStoreCategory")
    @PreAuthorize("hasAnyRole('admin','STORECATEGORY_ALL','STORECATEGORY_SELECT')")
    public ResponseEntity getYdyStoreCategorys(YdyStoreCategoryQueryCriteria criteria, Pageable pageable){
        List<YdyStoreCategoryDto> categoryDTOList = storeCategoryService.queryAll(criteria);
        return new ResponseEntity<>(storeCategoryService.buildTree(categoryDTOList),HttpStatus.OK);
    }

    @AopLog("新增商品分类")
    @ApiOperation(value = "新增商品分类")
    @PostMapping(value = "/ydyStoreCategory")
    @CacheEvict(cacheNames = ShopConstants.LYJ_SHOP_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','STORECATEGORY_ALL','STORECATEGORY_CREATE')")
    public ResponseEntity create(@Validated @RequestBody YdyStoreCategory resources){
        if(resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank(resources.getPic())) {
            throw new MyShopException("子分类图片必传");
        }

        boolean checkResult = storeCategoryService.checkCategory(resources.getPid());
        if(!checkResult) {
            throw new MyShopException("分类最多能添加2级哦");
        }

        return new ResponseEntity<>(storeCategoryService.save(resources),HttpStatus.CREATED);
    }

    @AopLog("修改商品分类")
    @ApiOperation(value = "修改商品分类")
    @CacheEvict(cacheNames = ShopConstants.LYJ_SHOP_REDIS_INDEX_KEY,allEntries = true)
    @PutMapping(value = "/ydyStoreCategory")
    @PreAuthorize("hasAnyRole('admin','STORECATEGORY_ALL','STORECATEGORY_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YdyStoreCategory resources){
        if(resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank(resources.getPic())) {
            throw new MyShopException("子分类图片必传");
        }

        if(resources.getId().equals(resources.getPid())){
            throw new MyShopException("自己不能选择自己哦");
        }

        boolean checkResult = storeCategoryService.checkCategory(resources.getPid());

        if(!checkResult) {
            throw new MyShopException("分类最多能添加2级哦");
        }

        storeCategoryService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @AopLog("删除商品分类")
    @ApiOperation(value = "删除商品分类")
    @CacheEvict(cacheNames = ShopConstants.LYJ_SHOP_REDIS_INDEX_KEY,allEntries = true)
    @DeleteMapping(value = "/ydyStoreCategory/{id}")
    @PreAuthorize("hasAnyRole('admin','STORECATEGORY_ALL','STORECATEGORY_DELETE')")
    public ResponseEntity delete(@PathVariable String id){
        String[] ids = id.split(",");
        for (String newId: ids) {
            this.delCheck(Integer.valueOf(newId));
            storeCategoryService.removeById(Integer.valueOf(newId));
        }
        return new ResponseEntity(HttpStatus.OK);
    }


    /**
     * 检测删除分类
     * @param id 分类id
     */
    private void delCheck(Integer id){
        int count = storeCategoryService.lambdaQuery()
                .eq(YdyStoreCategory::getPid,id)
                .count();
        if(count > 0) {
            throw new MyShopException("请先删除子分类");
        }

        int countP = storeProductService.lambdaQuery()
                .eq(YdyStoreProduct::getCateId,id)
                .count();

        if(countP > 0) {
            throw new MyShopException("当前分类下有商品不可删除");
        }
    }
}
